package com.paishen.peiniwan.module.date;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.paishen.common.dialog.BottomMenuDialog;
import com.paishen.common.dialog.BottomMenuDialog.BottomMenu;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.DateUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.ActivityCollector;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Balance;
import com.paishen.peiniwan.frame.http.entity.Book;
import com.paishen.peiniwan.frame.http.entity.DateInfo;
import com.paishen.peiniwan.frame.http.entity.DatePrice;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.StarView;
import com.paishen.peiniwan.module.message.EaseChatActivity;
import com.paishen.peiniwan.module.profile.ProfileInfoActivity;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.greenrobot.event.EventBus;

public class DateInfoActivity extends BaseActivity {
    public static final String EXTRA_DATE_INFO = "extra_date_info";
    private Book book;
    private DateInfo dateInfo;
    private User other;
    private boolean isSelfOrder, isSelfPay;
    private String[] date_status;

    private AlertDialog dlgCancelMake, dlgDateFinish;
    private BottomMenuDialog dlgBottomMenu;

    private TitleLayout layTitle;
    private View viewMenu, layState, layTel;
    private ImageView imgAvatar, imgTel;
    private TextView txSubject, txNickname, txTime, txLocation, txState, txTel;
    private StarView viewStar;
    private Button btnUp;
    private ViewGroup layTags;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dateInfo = (DateInfo) getIntent().getSerializableExtra(EXTRA_DATE_INFO);
        if (dateInfo == null || dateInfo.book == null || (book = dateInfo.book.get(0)) == null) {
            BaseUtil.showToast(R.string.error_data);
            finish();
            return;
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_info);

        isSelfPay = dateInfo.isself_pay;
        isSelfOrder = App.i().getUser().getId() == dateInfo.user.id;
        other = isSelfOrder ? book.user : dateInfo.user;
        date_status = getResources().getStringArray(R.array.date_status);

        layTitle = (TitleLayout) findViewById(R.id.lay_title);
        txState = (TextView) findViewById(R.id.tx_state);
        layState = findViewById(R.id.lay_state);
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        txSubject = (TextView) findViewById(R.id.tx_subject);
        txNickname = (TextView) findViewById(R.id.tx_nickname);
        txTime = (TextView) findViewById(R.id.tx_time);
        txLocation = (TextView) findViewById(R.id.tx_location);
        layTags = (ViewGroup) findViewById(R.id.lay_tags);
        viewStar = (StarView) findViewById(R.id.view_star);
        btnUp = (Button) findViewById(R.id.btn_up);
        layTel = findViewById(R.id.lay_tel);
        txTel = (TextView) findViewById(R.id.tx_tel);
        imgTel = (ImageView) findViewById(R.id.img_tel);

        layTel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + other.phone));
                startActivity(intent);
            }
        });
        findViewById(R.id.lay_other_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), ProfileInfoActivity.class);
                intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, other.id);
                v.getContext().startActivity(intent);
            }
        });

        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dateInfo.status == C.date.WAIT_RESPONSE_1) {
                    requestOrderSelectUser();
                } else if (dateInfo.status == C.date.WAIT_PAY_2) {
                    Intent intent = new Intent(DateInfoActivity.this, DatePayActivity.class);
                    intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_OID, dateInfo.id);
                    intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_PRICE, book.unit_price);
                    intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_BOOKID, book.id);
                    startActivity(intent);
                } else if (dateInfo.status == C.date.RUNNING_3 || dateInfo.status == C.date.WAIT_RUN_10 || dateInfo.status == C.date.COMPLETED_5) {
                    LogUtil.d("DateInfo selfPay:" + isSelfPay + "#selfOrder:" + isSelfOrder);
                    com.paishen.peiniwan.database.User dbOther = ModelConverter.mergeOrReplace(null, other);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, dbOther));

                    Intent intent = new Intent(v.getContext(), EaseChatActivity.class);
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, dbOther.getEasemob_username());
                    intent.putExtra(EaseChatFragment.EXTRA_OTHER_NICK, dbOther.getNickname());
                    intent.putExtra(EaseChatFragment.EXTRA_SELF_NICK, App.i().getUser().getNickname());


                    startActivity(intent);
                }
            }
        });

        Glide.with(this).load(other.head_img_url).bitmapTransform(App.i().getCropCircleTransformation())
                .into(imgAvatar);
        viewStar.setLightStarCount(other.good_rate);
        txNickname.setText(other.nickname);
        String date_from = DateUtil.convert(dateInfo.date_from, DateUtil.yyyy_MM_dd_HH_mm_ss, DateUtil.yyyy_MM_dd_HH_mm);
        txTime.setText(date_from);
        txLocation.setText(dateInfo.address);
        if (dateInfo.subject_type != null && dateInfo.subject_type.length > 0) {
            txSubject.setText(dateInfo.subject_type[0]);
        }
        List<String> baseInfos = Arrays.asList(other.profession,
                other.age,
                other.height,
                other.constellation,
                other.degree,
                other.city,
                other.weight,
                other.salary);
        int d5 = BaseUtil.dip2px(5);
        ViewGroup.MarginLayoutParams lpTags = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpTags.setMargins(d5, 0, d5, d5 * 3);
        for (String userProperties : baseInfos) {
            if (!TextUtils.isEmpty(userProperties)) {
                TextView txTag = new TextView(DateInfoActivity.this);
                txTag.setLayoutParams(lpTags);
                txTag.setTextColor(0xFF05131A);
                txTag.setTextSize(11);
                txTag.setPadding(d5 * 3, d5, d5 * 3, d5);
                txTag.setGravity(Gravity.CENTER);
                txTag.setText(userProperties);
                txTag.setBackgroundResource(R.drawable.date_shape_info_tag);
                layTags.addView(txTag);
            }
        }

        refreshUIByCurrState();
    }

    private void refreshUIByCurrState() {
        if (dateInfo.status == C.date.WAIT_RESPONSE_1) {
            layTel.setEnabled(false);
            txTel.setTextColor(0xFFB3B3B3);
            imgTel.setImageResource(R.mipmap.date_tel_disable);
            if (isSelfOrder) {
                // 自己是订单创建人就去约ta
                btnUp.setText(R.string.date_info_select);
                btnUp.setEnabled(true);
                btnUp.setTextColor(0xFFFFFFFF);
            } else {
                // 不然等待ta约
                btnUp.setText(R.string.date_info_wait_select);
                btnUp.setEnabled(false);
                btnUp.setTextColor(0xFFB3B3B3);
            }
        } else if (dateInfo.status == C.date.WAIT_PAY_2) {
            layTel.setEnabled(false);
            txTel.setTextColor(0xFFB3B3B3);
            imgTel.setImageResource(R.mipmap.date_tel_disable);
            // 待支付
            if (!isSelfPay) {
                btnUp.setText(R.string.date_info_wait_pay);
                btnUp.setEnabled(false);
                btnUp.setTextColor(0xFFB3B3B3);
            } else {
                btnUp.setText(R.string.date_info_pay);
                btnUp.setEnabled(true);
                btnUp.setTextColor(0xFFFFFFFF);
            }
        } else if (dateInfo.status == C.date.RUNNING_3 || dateInfo.status == C.date.WAIT_RUN_10 || dateInfo.status == C.date.COMPLETED_5) {
            layTel.setEnabled(true);
            txTel.setTextColor(0xFFFC4E52);
            imgTel.setImageResource(R.mipmap.date_tel_normal);
            // 进行中#待进行
            btnUp.setEnabled(true);
            btnUp.setTextColor(0xFFFFFFFF);
            btnUp.setText(R.string.date_info_chat);
        } else if (dateInfo.status == C.date.FAILURE_7 || dateInfo.status == C.date.CANCELLED_9) {
            layTel.setEnabled(false);
            txTel.setTextColor(0xFFB3B3B3);
            imgTel.setImageResource(R.mipmap.date_tel_disable);
            // 已取消# 未成功
            findViewById(R.id.lay_up).setVisibility(View.GONE);
        }

        if (dateInfo.status == C.date.WAIT_RUN_10) {
            viewMenu = LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
            ((ImageView) viewMenu).setImageResource(R.mipmap.common_more);
            viewMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showBottomMenuDialog();
                }
            });
        } else if (isSelfPay && dateInfo.status == C.date.RUNNING_3) {
            viewMenu = LayoutInflater.from(this).inflate(R.layout.layout_title_menu_text, null);
            ((TextView) viewMenu).setText(R.string.date_info_finish);
            viewMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showFinishConfirmDialog();
                }
            });
        } else {
            viewMenu = null;
        }
        layTitle.pushContent(makeBackView(), getString(R.string.date_info), viewMenu, false);

        layState.setVisibility(View.VISIBLE);
        txState.setText(date_status[dateInfo.status]);
        if (!isSelfOrder && dateInfo.status == C.date.WAIT_RESPONSE_1) {
            // txState.setText(getString(R.string.date_status_wait_select));
            txState.setText(date_status[C.date.RESPONSED_6]);
        }
        txState.setTextColor(0xFFFC4E52);
        int resState = R.mipmap.date_state_0;
        switch (dateInfo.status) {
            case C.date.WAIT_RESPONSE_1:
                txState.setTextColor(0xFFB3B3B3);
                resState = R.mipmap.date_state_0;
                break;
            case C.date.WAIT_PAY_2:
                resState = R.mipmap.date_state_1;
                break;
            case C.date.WAIT_RUN_10:
                resState = R.mipmap.date_state_2;
                break;
            case C.date.RUNNING_3:
                resState = R.mipmap.date_state_3;
                break;
            case C.date.COMPLETED_5:
            case C.date.CANCELLED_9:
            case C.date.FAILURE_7:
                resState = R.mipmap.date_state_4;
                break;
            default:
                layState.setVisibility(View.GONE);
                break;
        }
        layState.setBackgroundResource(resState);
    }

    private void requestOrderSelectUser() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();

        PnwHttpManager.Order.selectUser(TAG, dateInfo.id, book.id, new PnwOkCallbackAdapter<HttpRespData<DatePrice>>() {
            @Override
            public void onResponse(HttpRespData<DatePrice> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    com.paishen.peiniwan.database.User dbUser = ModelConverter.mergeOrReplace(null, other);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, dbUser));
                    // 如果是选择页面过来的则关闭
                    ActivityCollector.finishActivity(DateChooseActivity.class);

                    dateInfo.status = C.date.WAIT_PAY_2;
                    refreshUIByCurrState();
                    // 这里的price价格有可能来源是 DateChooseAcitivty 。selectUser接口可以拿到正确的价格。price使用它
                    float price = response.data.final_total;

                    if (isSelfPay) {
                        Intent intent = new Intent(DateInfoActivity.this, DatePayActivity.class);
                        intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_OID, dateInfo.id);
                        intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_PRICE, price);
                        intent.putExtra(DatePayActivity.EXTRA_DATE_PAY_BOOKID, book.id);
                        startActivity(intent);
                    }
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestOrderConfirmOrder() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();

        PnwHttpManager.Order.confirmOrder(TAG, dateInfo.id, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    dateInfo.status = C.date.WAIT_COMMENT_4;

                    Intent intent = new Intent(DateInfoActivity.this, DateCommentActivity.class);
                    intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, dateInfo);
                    startActivity(intent);
                    ActivityCollector.finishActivity(DateInfoActivity.class);

                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void showFinishConfirmDialog() {
        if (dlgDateFinish == null) {
            dlgDateFinish = new AlertDialog.Builder(this).setTitle(R.string.tips).setMessage(R.string.date_info_finish_message)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgDateFinish.dismiss();
                        }
                    }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgDateFinish.dismiss();
                            requestOrderConfirmOrder();
                        }
                    }).create();
        }
        dlgDateFinish.show();
    }

    private void showBottomMenuDialog() {
        if (dlgBottomMenu == null) {
            BottomMenu menu1 = new BottomMenu(getString(R.string.date_info_break),
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showCancelMakeDialog();
                            dlgBottomMenu.dismiss();
                        }
                    });
            List<BottomMenu> menuList = new ArrayList<>();
            menuList.add(menu1);
            dlgBottomMenu = new BottomMenuDialog.Builder(this).setMenuList(menuList).setCancelListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dlgBottomMenu.dismiss();
                }
            }).create();
        }
        dlgBottomMenu.show();
    }

    private void showCancelMakeDialog() {
        if (dlgCancelMake == null) {
            dlgCancelMake = new AlertDialog.Builder(this).setTitle(R.string.date_cancel)
                    .setMessage(isSelfPay ? R.string.date_cancel_make_payer : R.string.date_cancel_make_receiver)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgCancelMake.dismiss();
                        }
                    }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgCancelMake.dismiss();
                            requestOrderCancelOrder();
                        }
                    }).create();
        }
        dlgCancelMake.show();
    }


    private void requestOrderCancelOrder() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();

        PnwHttpManager.Order.cancelOrder(TAG, dateInfo.id, new PnwOkCallbackAdapter<HttpRespData<Balance>>() {
            @Override
            public void onResponse(HttpRespData<Balance> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data != null && response.data.amount != null) {
                        com.paishen.peiniwan.database.User login = App.i().getUser();
                        login.setAmount(response.data.amount);
                        EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));
                        EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_PROFILE));
                    }
                    finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    @Override
    public void onEventMainThread(BusEvent event) {
        super.onEventMainThread(event);
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_PAY_SUCCESS:
                    dateInfo.status = C.date.WAIT_RUN_10;
                    refreshUIByCurrState();
                    break;
                case BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_BE_SELECTED:
                    dateInfo.status = C.date.WAIT_PAY_2;
                    refreshUIByCurrState();
                    break;
                case BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_BE_CANCELLED:
                    BaseUtil.showToast(R.string.date_cancel_be_canceled);
                    dateInfo.status = C.date.CANCELLED_9;
                    refreshUIByCurrState();
                    break;
                case BusEvent.ACTION_REFRESH_DATE_INFO_STATUS_BE_COMPLETE:
                    dateInfo.status = C.date.WAIT_COMMENT_4;
                    Intent intent = new Intent(DateInfoActivity.this, DateCommentActivity.class);
                    intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, dateInfo);
                    startActivity(intent);
                    ActivityCollector.finishActivity(DateInfoActivity.class);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 更新我的约会状态
        EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_PROFILE_DATE));
    }
}
